//
//  InsCcUnzipTool.swift
//  ParsingCC
//
//  Created by insbridge-macmini1 on 2021/9/2.
//

import UIKit
import ZipArchive
import SwiftyJSON

class InsCcUnzipTool: NSObject {

    public static func ccmzToZip(filePath : String) -> (JSON, JSON){
        let fileName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension;
        let zipPath = NSHomeDirectory() + "/tmp/\(fileName).zip"
        if let data = NSData(contentsOfFile: filePath) {
            let version = data[0];
            var newData = data.subdata(with: NSMakeRange(1, data.count - 1));
            if version == 1 {
               
            }else if version == 2 {
                for i in 0..<newData.count {
                    if newData[i] % 2 == 0 {
                        newData[i] += 1;
                    }else {
                        newData[i] -= 1;
                    }
                }
            }
            if NSData(data: newData).write(to: URL(fileURLWithPath: zipPath), atomically: true) {
                try? FileManager.default.removeItem(atPath: filePath);
                let zipUnPath = NSHomeDirectory() + "/tmp/\(fileName)"
                if SSZipArchive.unzipFile(atPath: zipPath, toDestination: zipUnPath) {
                    try? FileManager.default.removeItem(atPath: zipPath);
                    if version == 1 {
                        if let data = NSData(contentsOfFile: zipUnPath + "/data.ccxml") {
                            if let data2 = NSData(contentsOfFile: zipUnPath + "/data.ccmid") {
                                try? FileManager.default.removeItem(atPath: zipUnPath);
                                return (JSON(data) , JSON(data2));
                            }
                        }
                    }else if version == 2 {
                        if let data = NSData(contentsOfFile: zipUnPath + "/score.json") {
                            if let data2 = NSData(contentsOfFile: zipUnPath + "/midi.json") {
                                try? FileManager.default.removeItem(atPath: zipUnPath);
                                return (JSON(data) , JSON(data2));
                            }
                        }
                    }
                }
            }
        }

        return (JSON() , JSON());
    }
    
    
    public static func Unzip(filePath : String) -> (Bool , String){
        let fileName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension;
        let destinationPath = NSHomeDirectory() + "/tmp/\(fileName)"
        if SSZipArchive.unzipFile(atPath: filePath, toDestination: destinationPath) {
            return (true , destinationPath);
        }
        return (false , "");
    }
    
    public static func removeAllFile() {
        let destinationPath = NSHomeDirectory() + "/tmp";
        try? FileManager.default.removeItem(atPath: destinationPath);
    }
    
    
}
